/**
 * 省市区三级联动
 */
let $province = $('select[name="provinceCode"]')
let $city = $('select[name="cityCode"]')
let $area = $('select[name="areaCode"]')

/**
 * 获取城市数据
 */
function getCity(provinceCode) {
    let city = []
    $.ajax({
        url: '/user/citiesby',
        data: {'provinceCode': provinceCode},
        type: 'post',
        async: false,
        dataType: 'json',
        error: function (error) {
            ms_show_toast(false, '后台获取城市信息出错!')
            console.error(error)
        },
        success: function (result) {
            if (result['code'] === CODE_SUCCESS)
                city = result['data']
        }
    })
    return city
}

/**
 * 获取市区数据
 */
function getArea(cityCode) {
    let area = []
    $.ajax({
        url: '/user/areaby',
        data: {'cityCode':cityCode},
        type: 'post',
        async: false,
        dataType: 'json',
        error: function (error) {
            ms_show_toast(false, '后台获取地区信息出错!')
            console.error(error)
        },
        success: function (result) {
            if (result['code'] === CODE_SUCCESS)
                area = result['data']
        }
    })
    return area
}
function ajaxPostAddressByUserCode(userCode){
    let address = {}
    $.ajax({
        url: '/user/addressby',
        type: 'POST',
        data: {'userCode' : userCode},
        dataType: 'json',
        async: false,
        error: function (err){
            ms_show_toast(false, err.responseText)
            console.error(err.responseText)
        },
        success: function (result){
            if(result['code'] === CODE_SUCCESS){
                address = result['data']
            }
        }
    })
    return address
}
/**
 *
 * 动态渲染数据到 select标签
 */
function render($select, jsonData, selectFirst){
    $select.html('')
    for(let i in jsonData){
        $select.append(`<option value="${jsonData[i].code}">${jsonData[i].name}</option>`)
    }
    if(selectFirst === true)
        $select.children('option').attr('checked', true)
}
/**
 * 初始化
 */
function renderAddress(user_address){
    console.log(user_address)
        $.ajax({
            url: '/user/provinces',
            type: 'post',
            dataType: 'json',
            error: function (error) {
                ms_show_toast(false, '后台获取地址信息出错!')
                console.error(error)
            },
            success: function (result) {
                let provinceCode = result['data'][0]['code']
                // 先获取所有的省，并选择第一个省
                let user_province = user_address['province']
                // 如果用户已经有省份，就指定这个省份，否则就默认第一个
                if(typeof(user_province) == "string") {
                    provinceCode = user_province
                    render($province, result['data'], false)
                    $province.val(provinceCode)
                } else
                    render($province, result['data'], true)
                // 渲染市
                let cities = getCity(provinceCode)
                let cityCode = cities[0]['code']
                let user_city = user_address['city']
                if(typeof(user_city) == "string"){
                    cityCode = user_city
                    render($city, cities, false)
                    $city.val(cityCode)
                }
                    else render($city, cities, true)

                // 渲染区
                let areas = getArea(cityCode)
                let areaCode = areas[0]['code']
                let user_area = user_address['area']
                if(typeof(user_area) == "string"){
                    areaCode = user_area
                    render($area, areas, false)
                    $area.val(areaCode)
                }else
                    render($area, areas, true)
            }
        })
}

/**
 * 当选择市区
 */
$city.change(function(){
    let cityCode = $(this).val()
    // 获取地区
    let area = getArea(cityCode)
    // 渲染，并默认选择第一个
    render($area, area, true)
})
/**
 * 当选择省份
 */
$province.change(function (){
    let provinceCode = $(this).val()
    // 获取市区
    let cities = getCity(provinceCode)
    // 渲染, 并默认选择第一个
    render($city, cities, true)
    // 此时市区发生变化，调用其变化函数
    $city.change()

})

